#include <stdio.h>

/* get n bits from persition p */
unsigned getbits(unsigned x, int p, int n) {
    return (x >> (p+1-n)) & ~(~0 << n);
}
/* ex 2-6 */
unsigned setbits(unsigned x, int p, int n, unsigned y) {
    return (x | (~(~0 << n) << (p+1-n))) & (y << (p+1-n));
}

/* ex 2-7 */
/* 将x 从p开始的n位取反，其它位不变 */
unsigned invert(unsigned x, int p, int n) {
    return x ^ (~(~0 << n) << (p+1-n));
}

/* ex 2-8 循环右移*/
unsigned rightrot(unsigned x, int n) {
    return ((x & ~(~0 << n)) << (sizeof(unsigned)*8 - n)) | (x >> n);
}

int main(int argc, char *argv[])
{
    unsigned x = 0xe0;
    unsigned y = 0xe2;
    int p = 2, n = 2;
    printf("0x%x, %d, %d, getbits: %x\n", x, p, n, getbits(x, p, n));
    printf("0x%x, %d, %d, 0x%x setbits: %x\n", x, p, n, y, setbits(x, p, n, y));
    x = 0xff;
    p = 4; n = 3;
    printf("0x%x, %d, %d, invert: 0x%x\n", x, p, n, invert(x, p, n));
    n = 4;
    printf("0x%x, %d, rightrot: 0x%x\n", y, n, rightrot(y, n));
    return 0;
}
